const http = require("http"),
	querystring = require('querystring');

const itroninfo = {
	APP_ID: "1000000006",
	APP_KEY: "DXT18ATJKoos4DKl0qugP8kePXljbzWo",
	REDIRECT_URI: "http://iblockly.11.com.cn/user/setToken/itron"
};

const setToken = (req, res, cb) => {
	let code = req.query.code;
	let postData = querystring.stringify({
		'client_id': itroninfo.APP_ID,
		'client_secret': itroninfo.APP_KEY,
		'grant_type': 'authorization_code',
		'redirect_uri': itroninfo.REDIRECT_URI,
		'code': code
	});

	let options = {
		hostname: "www.11.com.cn",
		port: 80,
		method: 'POST',
		path: "/oauth/token.php",
		headers: {
			'Content-Type': 'application/x-www-form-urlencoded',
			'Content-Length': Buffer.byteLength(postData)
		}
	};

	let req1 = http.request(options, (res1) => {
		res1.on('data', (d) => {
			// console.log('BODY: ' + d);
			d = JSON.parse(d);

			function getUserInfo() {
				let path = "/oauth/userinfo_api.php?oauth_token=" + d.access_token;
				options = {
					hostname: "www.11.com.cn",
					port: 80,
					method: 'GET',
					path: path
				};
				let req2 = http.request(options, (res2) => {
					res2.on('data', (d2) => {
						d2 = JSON.parse(d2);
						// console.log('BODY2: ' + d2);
						let sessionStore = req.sessionStore;
						let sid = req.query.state;
						sessionStore.load(sid, (err, sess) => {
							if (err) {
								res.redirect(301, '/close.html');
								console.error(err);
							} else if (!sess) {
								res.redirect(301, '/close.html');
							} else if (d2.errcode) {
								// console.log(d2);
								res.send(JSON.stringify({
									result: -1,
									msg: "登陆错误，请重试",
									// error: error
								}));
								console.error(err);
							} else {
								sess.userInfo = {
									userType: "itron",
									id: "itron_" + d2.uid,
									nickname: d2.username,
									verified: true,
									prop: d2
								};
								sess.save((err) => {
									if (err) {
										console.error(err);
									}
								});
								res.redirect(301, '/close.html');
								// console.log("set token\n" + sess.id + "\n" + sess);
								cb(sess.userInfo);
							}
						});
					});
				});

				req2.on('error', (err) => {
					res.send(JSON.stringify({
						result: -1,
						msg: "获取用户信息出错",
						// error: e
					}));
					console.error(err);
				});
				req2.end();
			}
			getUserInfo();
		});
	});

	req1.on('error', (err) => {
		res.send(JSON.stringify({
			result: -1,
			msg: "登陆错误，请重试",
			// error: e
		}));
		console.error(err);
	});
	req1.write(postData);
	req1.end();
};
module.exports.sesetToken = setToken;